//
//  WDEditHeadView.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2017/2/10.
//  Copyright © 2017年 王笛. All rights reserved.
//

#import "WDEditHeadView.h"
#import "WDLoan.h"
#import "WDMoneyTextField.h"
#import "WDProduct.h"
#import "WDCarTypeController.h"
#import "WDFinancialProductController.h"
#import "WDBusinessListController.h"
#import "WDStseries.h"
#import "WDCarTypeSheet.h"
#import "WDCustomSheet.h"

@interface WDEditHeadView ()<UITextFieldDelegate, WDCarTypeSheetDelegate, WDCustomSheetDelegate, UITextViewDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameTextF;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextF;
@property (weak, nonatomic) IBOutlet UILabel *carTypeLabel;
@property (weak, nonatomic) IBOutlet UILabel *carBrandLabel;
@property (weak, nonatomic) IBOutlet WDMoneyTextField *carPriceTextF;
@property (weak, nonatomic) IBOutlet UILabel *productLabel;
@property (weak, nonatomic) IBOutlet WDMoneyTextField *loanMoneyTextF;
@property (weak, nonatomic) IBOutlet UILabel *termLabel;
/** 所属商户 */
@property (weak, nonatomic) IBOutlet UILabel *businessLabel;
/** 备注 */
@property (weak, nonatomic) IBOutlet UITextView *remarkTextV;
@property (weak, nonatomic) IBOutlet UILabel *lastLabel;
/** 备注占位文字 */
@property (weak, nonatomic) IBOutlet UILabel *remarkPlaceLabel;
@property (assign, nonatomic) BOOL isHaveDian;
/** 分期数组 */
@property (nonatomic, strong) NSArray *terms;
/** textView高度 */
@property (assign, nonatomic) CGFloat textViewH;

@end

@implementation WDEditHeadView

- (void)awakeFromNib
{
    [super awakeFromNib];
    
    self.carPriceTextF.limit.maxV = @"999.999";
    self.carPriceTextF.limit.digit = 3;
    
    self.loanMoneyTextF.limit.maxV = @"999.999";
    self.loanMoneyTextF.limit.digit = 3;
    
    //加手势
    UITapGestureRecognizer *carTypeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(carTypeTap)];
    [self.carTypeLabel addGestureRecognizer:carTypeTap];
    
    UITapGestureRecognizer *carBrandTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(seriesTap)];
    [self.carBrandLabel addGestureRecognizer:carBrandTap];
    
    UITapGestureRecognizer *termTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(termTap)];
    [self.termLabel addGestureRecognizer:termTap];
    
    UITapGestureRecognizer *productTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(productTap)];
    [self.productLabel addGestureRecognizer:productTap];
    
    UITapGestureRecognizer *businessTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(businessTap)];
    [self.businessLabel addGestureRecognizer:businessTap];
    
     
}

- (void)carTypeTap
{
    
    WDLog(@"点击了跳转车类型");
    NSArray *buttons = @[@"icon-ershouche", @"icon-xinche"];
    NSArray *seleBtns = @[@"icon-ershouche-xuanzhong", @"icon-xinche-xuanzhong",];
    WDCarTypeSheet *carTypeSheet = [[WDCarTypeSheet alloc] initWithButtons:buttons seleBtn:seleBtns];
    carTypeSheet.delegate = self;
    carTypeSheet.title = @"请选择车辆类型";
    
    if ([_delegate isKindOfClass:[UIViewController class]]) {
        
        UIViewController *tempVC = (UIViewController *)_delegate;
        [tempVC.view addSubview:carTypeSheet];
    }
    
    
}

- (void)seriesTap
{
    WDLog(@"点击了车系");
    WDCarTypeController *carTypeV = [[WDCarTypeController alloc] init];
    
    carTypeV.view.backgroundColor = WDBackColor;
    
    if ([_delegate respondsToSelector:@selector(jumpPage:viewController:)]) {
        
        //block传值
        __weak typeof (self)weakSelf = self;
        
        carTypeV.carType = ^(WDStseries *stseries ,NSString *carType){
            
            NSString *carName = [NSString stringWithFormat:@"%@ %@", carType, stseries.name];
            
            weakSelf.loan.brand_name = carType;
            weakSelf.loan.brand_id = stseries.brand_id;
            weakSelf.loan.series_id = stseries.id;
            weakSelf.loan.series_name = stseries.name;
            weakSelf.carBrandLabel.text = carName;
                        };
        
        [_delegate jumpPage:WDJumpTypeSeries viewController:carTypeV];
    }

}

- (void)productTap
{
    WDLog(@"点击了产品");
    WDFinancialProductController *productV = [[WDFinancialProductController alloc] init];
    
    productV.view.backgroundColor = WDBackColor;
    
    if ([_delegate respondsToSelector:@selector(jumpPage:viewController:)]) {
        
        if ([self.loanMoneyTextF.text isEqualToString:@""]) {
            
            [WDPromptBox showPromptBoxWithMassage:@"请输入贷款金额"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        } else if ([self.termLabel.text isEqualToString:@""]) {
            [WDPromptBox showPromptBoxWithMassage:@"请输入还款期数"];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [SVProgressHUD dismiss];
            });
            
        } else {
            //跳转金融产品
            WDFinancialProductController *tempV = [[WDFinancialProductController alloc] init];
            tempV.loanProduct = YES;
            tempV.loanAmount = self.loanMoneyTextF.text;
            tempV.loanTerm = self.termLabel.text;
            if ([self.carTypeLabel.text isEqualToString:@"新车"]) {
                tempV.loanCarType = NO;
            } else {
                tempV.loanCarType = YES;
            }
            
            __weak typeof (self)weakSelf = self;
            tempV.productData = ^(WDProduct *product){
                
                weakSelf.loan.product_id = product.id;
                self.loan.product_name = [NSString stringWithFormat:@"%@ %@", product.parent_name, product.name];
                weakSelf.productLabel.text = [NSString stringWithFormat:@"%@ %@", product.parent_name, product.name];
            };
            
            tempV.view.backgroundColor = WDBackColor;
            [_delegate jumpPage:WDJumpTypeProduct viewController:tempV];
        }
    }
}

- (void)termTap
{
    WDLog(@"点击了贷款分期");
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    
    NSArray *productMessage = [manager selectWithTable:NSStringFromClass([WDProduct class])];
    
    WDProduct *tempProduct;
    for (tempProduct in productMessage) {
        if ([tempProduct.id isEqualToString:self.loan.product_id]) {
            self.terms = [tempProduct.term componentsSeparatedByString:@","];
            break;
        }
    }
    
    self.terms = [tempProduct.term componentsSeparatedByString:@","];
    WDCustomSheet *sheet = [[WDCustomSheet alloc] initWithButtons:self.terms isOriginal:YES];
    sheet.delegate = self;
    sheet.title = @"还款期数";
    
    if ([_delegate isKindOfClass:[UIViewController class]]) {
        
        UIViewController *tempVC = (UIViewController *)_delegate;
        [tempVC.view addSubview:sheet];
    }
    
}

- (void)businessTap
{
    WDLog(@"点击了商户");
    
    //选择商户
    WDBusinessListController *tempV = [[WDBusinessListController alloc] init];
    
    __weak typeof (self)weakSelf = self;
    
    tempV.businessName = ^(NSString *businessName, NSString *businessID){
        weakSelf.loan.supplier_name = businessName;
        
        weakSelf.loan.supplier_id = businessID;
    };
    
    tempV.view.backgroundColor = WDBackColor;
    
    [_delegate jumpPage:WDJumpTypeBusiness viewController:tempV];
}

+ (instancetype)editHeadView
{
    WDEditHeadView *editHeadView = [[[NSBundle mainBundle] loadNibNamed:NSStringFromClass(self) owner:nil options:nil] lastObject];
    
    return editHeadView;
}

- (void)setLoan:(WDLoan *)loan
{
    _loan = loan;
    
    self.nameTextF.text = loan.user_name;
    self.phoneTextF.text = loan.phone;
    
    if ([loan.car_type isEqualToString:@"0"]) {
        
        self.carTypeLabel.text = @"新车";
    } else {
        
        self.carTypeLabel.text = @"二手车";
    }
    
    self.carBrandLabel.text = [NSString stringWithFormat:@"%@ %@", loan.brand_name, self.loan.series_name];
    
    self.carPriceTextF.text = loan.car_price;
    
    self.productLabel.text = loan.product_name;
    
    self.loanMoneyTextF.text = loan.loan_amount;
    
    self.termLabel.text = loan.pay_periods;
    
    self.businessLabel.text = loan.supplier_name;
    
    self.remarkTextV.text = loan.remark;
    CGSize size = [self sizeWithString:loan.remark font:[UIFont systemFontOfSize:14] constraintSize:CGSizeMake(WDScreenW - 40, MAXFLOAT)];
    self.textViewH = size.height;
    
    [self.remarkTextV makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(self.textViewH + 20);
    }];
    
    [self layoutIfNeeded];
    
    [self.remarkTextV layoutIfNeeded];
    
    [self.nameTextF layoutIfNeeded];
    
    WDLog(@"%f", CGRectGetMaxY(self.nameTextF.frame));
    
    WDLog(@"%f", CGRectGetMaxY(self.productLabel.frame));
    
    WDLog(@"%f", CGRectGetMaxY(self.termLabel.frame));
    
    loan.detailHeadH = CGRectGetMaxY(self.lastLabel.frame) + 20;
}

#pragma mark - <WDCarTypeSheetDelegate>
- (void)carTypeSheet:(WDCarTypeSheet *)sheet clickButton:(NSUInteger)index
{
    if (index == 0) {//二手车
        self.loan.car_type = @"1";
        self.carTypeLabel.text = @"二手车";
    } else {//新车
        self.loan.car_type = @"0";
        self.carTypeLabel.text = @"新车";
    }
}

#pragma mark - <WDCustomSheetDelegate>
- (void)customSheet:(WDCustomSheet *)sheet clickButton:(NSUInteger)index
{
    self.termLabel.text = self.terms[index];
    self.loan.pay_periods = self.terms[index];
}

#pragma mark - <UITextFieldDelegate>
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
{
    if (textField == self.nameTextF) {
        self.loan.user_name = textField.text;
    } else if (textField == self.phoneTextF) {
        self.loan.phone = textField.text;
    } else if (textField == self.carPriceTextF){
        self.loan.car_price = textField.text;
    } else if (textField == self.loanMoneyTextF) {
        self.loan.loan_amount = textField.text;
    }
    return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == self.nameTextF) {//验证姓名
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        
        NSInteger selectedLength = range.length;
        
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 20) {
            
            return NO;
        }
        
    } else if (textField == self.phoneTextF) {//验证手机
        
        if (string.length == 0) return YES;
        
        NSInteger existedLength = textField.text.length;
        
        NSInteger selectedLength = range.length;
        
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            
            return NO;
        }
        
    } else {//预留其他
        return YES;
    }
    
    return YES;
}

#pragma mark - <UITextViewDelegate>
- (void)textViewDidChange:(UITextView *)textView
{
    self.remarkPlaceLabel.hidden = YES;
    
    if ([textView.text isEqualToString:@""]) {
        
        self.remarkPlaceLabel.hidden = NO;
    }
    
    CGSize textSize = [self sizeWithString:textView.text font:[UIFont systemFontOfSize:14] constraintSize:CGSizeMake(WDScreenW - 40, MAXFLOAT)];
    
    WDLog(@"height = %f", textSize.height);
    
    if (textSize.height != self.textViewH) {
        
        self.textViewH = textSize.height;
        
        [self.remarkTextV updateConstraints:^(MASConstraintMaker *make) {
            make.height.equalTo(self.textViewH + 20);
        }];
        
        [self layoutIfNeeded];
        
        [self.remarkTextV layoutIfNeeded];
        
        WDLog(@"%f", CGRectGetMaxY(self.carTypeLabel.frame));
        
        WDLog(@"%f", CGRectGetMaxY(self.productLabel.frame));
        
        WDLog(@"%f", CGRectGetMaxY(self.termLabel.frame));
        
        self.loan.detailHeadH = CGRectGetMaxY(self.lastLabel.frame) + 20;
        
        [_delegate updataHeadViewH:self.loan.detailHeadH];
    }
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    self.loan.remark = self.remarkTextV.text;
    
    if (!textView.text || [textView.text isEqualToString:@""]) {
        
        self.remarkPlaceLabel.hidden = NO;
        
    } else {
        
        self.remarkPlaceLabel.hidden = YES;
    }
}

@end
